package com.humingzhang.client.oss;

import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.OSSObject;
import com.humingzhang.client.FileClient;
import org.apache.commons.io.IOUtils;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

/**
 * OSS 存储客户端
 *
 * @author minghu.zhang
 */
public class OssFileClient implements FileClient {

    private final OSSClient ossClient;
    private final OssConfig ossConfig;

    public OssFileClient(OssConfig ossConfig) {
        this.ossConfig = ossConfig;
        this.ossClient = new OSSClient(ossConfig.getEndpoint(), ossConfig.getAccessKeyId(),
                ossConfig.getAccessKeySecret());
    }

    /***
     * 上传文件
     */
    @Override
    public String upload(String path, InputStream in) {
        try {
            if (ossClient.doesObjectExist(ossConfig.getBucketName(), path)) {
                throw new RuntimeException("文件已存在," + path);
            }

            ossClient.putObject(ossConfig.getBucketName(), path, in);
            return path;
        } catch (Exception e) {
            throw new RuntimeException("文件存储异常," + e.getMessage(), e);
        }
    }

    @Override
    public void download(String path, OutputStream output) throws IOException {
        if (!ossClient.doesObjectExist(ossConfig.getBucketName(), path)) {
            throw new RuntimeException("文件不存在," + path);
        }
        OSSObject ossObject = ossClient.getObject(ossConfig.getBucketName(), path);
        IOUtils.copy(ossObject.getObjectContent(), output);
        ossObject.close();
    }

    @Override
    public void delete(String path) {
        if (!ossClient.doesObjectExist(ossConfig.getBucketName(), path)) {
            throw new RuntimeException("文件不存在," + path);
        }
        if (ossClient.doesObjectExist(ossConfig.getBucketName(), path)) {
            ossClient.deleteObject(ossConfig.getBucketName(), path);
        }
    }

    @Override
    public void close() {
        ossClient.shutdown();
    }

}
